<template>
  <view class="container">
    <!-- 表单 -->
    <view class="form-container" v-if="formLoaded">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">
          <text>基本信息</text>
        </view>
        
        <view class="form-item">
          <text class="form-label required">名称</text>
          <input 
            class="form-input" 
            v-model="cropForm.name" 
            placeholder="请输入农作物名称"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label required">类型</text>
          <picker 
            mode="selector" 
            :range="cropTypes" 
            @change="onTypeChange"
            :value="cropTypeIndex"
          >
            <view class="picker">
              <text>{{ cropForm.crop_type || '请选择农作物类型' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">品种</text>
          <input 
            class="form-input" 
            v-model="cropForm.variety" 
            placeholder="请输入品种"
          />
        </view>
      </view>
      
      <!-- 种植信息 -->
      <view class="form-section">
        <view class="section-title">
          <text>种植信息</text>
        </view>
        
        <view class="form-item">
          <text class="form-label required">种植位置</text>
          <picker 
            mode="selector" 
            :range="locations" 
            @change="onLocationChange"
            :value="locationIndex"
          >
            <view class="picker">
              <text>{{ cropForm.location || '请选择种植位置' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label required">种植日期</text>
          <picker 
            mode="date" 
            :value="plantDateStr" 
            @change="onPlantDateChange"
          >
            <view class="picker">
              <text>{{ plantDateStr || '请选择种植日期' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">收获日期</text>
          <picker 
            mode="date" 
            :value="harvestDateStr" 
            @change="onHarvestDateChange"
            :disabled="cropForm.status !== 1"
          >
            <view class="picker" :class="{ 'picker-disabled': cropForm.status !== 1 }">
              <text>{{ harvestDateStr || '请选择收获日期' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">种植面积(平方米)</text>
          <input 
            class="form-input" 
            v-model="cropForm.area" 
            type="digit"
            placeholder="请输入种植面积"
          />
        </view>
      </view>
      
      <!-- 状态信息 -->
      <view class="form-section">
        <view class="section-title">
          <text>状态信息</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">状态</text>
          <picker 
            mode="selector" 
            :range="statusOptions" 
            range-key="label"
            @change="onStatusChange"
            :value="statusIndex"
          >
            <view class="picker">
              <text>{{ getStatusText(cropForm.status) }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">描述</text>
          <textarea 
            class="form-textarea" 
            v-model="cropForm.description" 
            placeholder="请输入描述信息"
            maxlength="500"
          />
        </view>
      </view>
      
      <!-- 图片上传 -->
      <view class="form-section">
        <view class="section-title">
          <text>农作物图片</text>
        </view>
        
        <view class="image-upload">
          <view class="upload-preview" v-if="cropForm.image">
            <image :src="cropForm.image" mode="aspectFill"></image>
            <view class="remove-image" @tap="removeImage">
              <uni-icons type="close" size="16" color="#ffffff"></uni-icons>
            </view>
          </view>
          
          <view class="upload-btn" v-else @tap="chooseImage">
            <uni-icons type="camera" size="24" color="#999999"></uni-icons>
            <text>上传图片</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载中 -->
    <view class="loading" v-else>
      <text>加载中...</text>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <view class="cancel-btn" @tap="goBack">
        <text>取消</text>
      </view>
      <view class="save-btn" @tap="saveCrop">
        <text>保存</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, reactive, computed, onMounted } from 'vue';
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';

// 是否为编辑模式
const isEdit = ref(false);
const cropId = ref('');
const formLoaded = ref(false);

// 农作物表单数据
const cropForm = reactive({
  name: '',
  crop_type: '',
  variety: '',
  plant_date: null,
  harvest_date: null,
  location: '',
  area: '',
  status: 0,
  description: '',
  image: ''
});

// 农作物类型
const cropTypes = [
  '蔬菜',
  '水果',
  '粮食',
  '经济作物',
  '药材',
  '其他'
];

// 种植位置
const locations = [
  '1号大棚',
  '2号大棚',
  '3号大棚',
  '露天农田',
  '实验区'
];

// 状态选项
const statusOptions = [
  { value: 0, label: '种植中' },
  { value: 1, label: '已收获' },
  { value: 2, label: '已废弃' }
];

// 选择器索引
const cropTypeIndex = computed(() => {
  const index = cropTypes.findIndex(item => item === cropForm.crop_type);
  return index >= 0 ? index : 0;
});

const locationIndex = computed(() => {
  const index = locations.findIndex(item => item === cropForm.location);
  return index >= 0 ? index : 0;
});

const statusIndex = computed(() => {
  const index = statusOptions.findIndex(item => item.value === cropForm.status);
  return index >= 0 ? index : 0;
});

// 日期格式化
const formatDateToStr = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 日期字符串
const plantDateStr = computed(() => formatDateToStr(cropForm.plant_date));
const harvestDateStr = computed(() => formatDateToStr(cropForm.harvest_date));

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  return currentPage.$page?.options || {};
};

// 初始化表单
const initForm = async () => {
  formLoaded.value = false;
  
  try {
    const params = getPageParams();
    cropId.value = params.id;
    
    if (cropId.value) {
      // 编辑模式
      isEdit.value = true;
      await getCropDetail();
    } else {
      // 添加模式
      isEdit.value = false;
      formLoaded.value = true;
    }
  } catch (error) {
    console.error('初始化表单失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    });
    goBack();
  }
};

// 获取农作物详情
const getCropDetail = async () => {
  try {
    const { result } = await uniCloud.callFunction({
      name: 'crop',
      data: {
        action: 'get',
        data: {
          id: cropId.value
        }
      }
    });
    
    if (result.code === 200) {
      // 填充表单数据
      Object.assign(cropForm, result.data);
      formLoaded.value = true;
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
      goBack();
    }
  } catch (error) {
    console.error('获取农作物详情失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
    goBack();
  }
};

// 选择农作物类型
const onTypeChange = (e) => {
  const index = e.detail.value;
  cropForm.crop_type = cropTypes[index];
};

// 选择种植位置
const onLocationChange = (e) => {
  const index = e.detail.value;
  cropForm.location = locations[index];
};

// 选择种植日期
const onPlantDateChange = (e) => {
  cropForm.plant_date = new Date(e.detail.value).getTime();
};

// 选择收获日期
const onHarvestDateChange = (e) => {
  cropForm.harvest_date = new Date(e.detail.value).getTime();
};

// 选择状态
const onStatusChange = (e) => {
  const index = e.detail.value;
  cropForm.status = statusOptions[index].value;
  
  // 如果状态为已收获，但没有设置收获日期，则设置为当前日期
  if (cropForm.status === 1 && !cropForm.harvest_date) {
    cropForm.harvest_date = Date.now();
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const option = statusOptions.find(item => item.value === status);
  return option ? option.label : '未知';
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 上传图片到云存储
      const tempFilePath = res.tempFilePaths[0];
      uni.showLoading({ title: '上传中...' });
      
      // 使用文件原始名称作为cloudPath
      const cloudPath = res.tempFiles[0].name;
      
      uniCloud.uploadFile({
        filePath: tempFilePath,
        cloudPath: cloudPath,
        success: (uploadRes) => {
          console.log('上传成功', uploadRes);
          // 保存文件的云存储路径
          cropForm.image = uploadRes.fileID;
        },
        fail: (err) => {
          console.error('上传失败', err);
          uni.showToast({
            title: '图片上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  });
};

// 移除图片
const removeImage = () => {
  cropForm.image = '';
};

// 表单验证
const validateForm = () => {
  if (!cropForm.name.trim()) {
    uni.showToast({
      title: '请输入农作物名称',
      icon: 'none'
    });
    return false;
  }
  
  if (!cropForm.crop_type) {
    uni.showToast({
      title: '请选择农作物类型',
      icon: 'none'
    });
    return false;
  }
  
  if (!cropForm.location) {
    uni.showToast({
      title: '请选择种植位置',
      icon: 'none'
    });
    return false;
  }
  
  if (!cropForm.plant_date) {
    uni.showToast({
      title: '请选择种植日期',
      icon: 'none'
    });
    return false;
  }
  
  return true;
};

// 保存农作物
const saveCrop = async () => {
  if (!validateForm()) return;
  
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    // 处理数值类型
    if (cropForm.area) {
      cropForm.area = parseFloat(cropForm.area);
    }
    
    const action = isEdit.value ? 'update' : 'add';
    const data = { ...cropForm };
    
    if (isEdit.value) {
      data._id = cropId.value;
    }
    
    const { result } = await uniCloud.callFunction({
      name: 'crop',
      data: {
        action,
        data
      }
    });
    
    if (result.code === 200) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '添加成功',
        icon: 'success'
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        goBack();
      }, 1500);
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存农作物失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 生命周期钩子
onMounted(() => {
  initForm();
});
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-bottom: 80px;
  padding-top: 10px; /* 添加顶部内边距 */
}

/* 表单容器 */
.form-container {
  flex: 1;
  padding: 10px;
}

/* 表单分区 */
.form-section {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 10px;
  overflow: hidden;
}

.section-title {
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title text {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

/* 表单项 */
.form-item {
  display: flex;
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 120px;
  font-size: 14px;
  color: #666666;
  padding-top: 2px;
}

.required:after {
  content: '*';
  color: #ff4d4f;
  margin-left: 2px;
}

.form-input {
  flex: 1;
  height: 24px;
  font-size: 14px;
  color: #333333;
  text-align: right;
}

.form-textarea {
  flex: 1;
  height: 80px;
  font-size: 14px;
  color: #333333;
  text-align: right;
}

.picker {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.picker text:first-child {
  font-size: 14px;
  color: #333333;
  margin-right: 5px;
}

.picker .iconfont {
  font-size: 14px;
  color: #cccccc;
}

.picker-disabled text {
  color: #999999;
}

/* 图片上传 */
.image-upload {
  padding: 15px;
  display: flex;
  justify-content: center;
}

.upload-btn {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-btn .iconfont {
  font-size: 24px;
  color: #999999;
  margin-bottom: 8px;
}

.upload-btn text:last-child {
  font-size: 14px;
  color: #999999;
}

.upload-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
}

.upload-preview image {
  width: 100%;
  height: 100%;
}

.remove-image {
  position: absolute;
  top: 0;
  right: 0;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 0 0 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-image .iconfont {
  font-size: 16px;
  color: #ffffff;
}

/* 加载中 */
.loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading text {
  font-size: 14px;
  color: #999999;
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  height: 60px;
  background-color: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.cancel-btn, .save-btn {
  flex: 1;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background-color: #f5f5f5;
}

.cancel-btn text {
  font-size: 16px;
  color: #666666;
}

.save-btn {
  background-color: #4CAF50;
}

.save-btn text {
  font-size: 16px;
  color: #ffffff;
}

/* 图标样式 */
.iconfont {
  font-family: "iconfont";
}

.icon-back:before {
  content: "\e679";
}

.icon-right:before {
  content: "\e6a3";
}

.icon-camera:before {
  content: "\e6ac";
}

.icon-close:before {
  content: "\e69e";
}
</style> 